import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品管理系统图形用户界面
 * 使用Swing框架实现
 */
public class ProductGUI extends JFrame {
    private static final String PRODUCT_FILE_PATH = "products.dat";
    private JTabbedPane tabbedPane;
    private DefaultListModel<String> productListModel;
    private JList<String> productList;
    private JTextArea detailsArea;
    private JTextField searchField;
    private JButton addButton, deleteButton, updateButton, searchButton, refreshButton;
    
    /**
     * 构造方法，初始化GUI界面
     */
    public ProductGUI() {
        super("电商系统商品管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setLocationRelativeTo(null); // 窗口居中
        
        initComponents();
        refreshProductList();
    }
    
    /**
     * 初始化所有UI组件
     */
    private void initComponents() {
        tabbedPane = new JTabbedPane();
        
        // 主界面选项卡
        JPanel mainPanel = createMainPanel();
        tabbedPane.addTab("商品管理", mainPanel);
        
        // 统计信息选项卡
        JPanel statsPanel = createStatsPanel();
        tabbedPane.addTab("统计信息", statsPanel);
        
        // 关于选项卡
        JPanel aboutPanel = createAboutPanel();
        tabbedPane.addTab("关于系统", aboutPanel);
        
        add(tabbedPane);
    }
    
    /**
     * 创建主界面面板
     */
    private JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // 顶部搜索栏
        JPanel searchPanel = new JPanel(new BorderLayout(5, 5));
        searchField = new JTextField(30);
        searchButton = new JButton("搜索");
        refreshButton = new JButton("刷新");
        
        searchPanel.add(searchField, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
        buttonPanel.add(searchButton);
        buttonPanel.add(refreshButton);
        searchPanel.add(buttonPanel, BorderLayout.EAST);
        
        panel.add(searchPanel, BorderLayout.NORTH);
        
        // 中间商品列表和详情
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(250);
        
        // 左侧商品列表
        productListModel = new DefaultListModel<>();
        productList = new JList<>(productListModel);
        productList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        productList.addListSelectionListener(e -> showProductDetails());
        
        JScrollPane listScrollPane = new JScrollPane(productList);
        listScrollPane.setBorder(BorderFactory.createTitledBorder("商品列表"));
        splitPane.setLeftComponent(listScrollPane);
        
        // 右侧商品详情
        detailsArea = new JTextArea();
        detailsArea.setEditable(false);
        detailsArea.setLineWrap(true);
        detailsArea.setWrapStyleWord(true);
        JScrollPane detailsScrollPane = new JScrollPane(detailsArea);
        detailsScrollPane.setBorder(BorderFactory.createTitledBorder("商品详情"));
        splitPane.setRightComponent(detailsScrollPane);
        
        panel.add(splitPane, BorderLayout.CENTER);
        
        // 底部按钮
        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        addButton = new JButton("添加商品");
        deleteButton = new JButton("删除商品");
        updateButton = new JButton("更新商品");
        
        actionPanel.add(addButton);
        actionPanel.add(deleteButton);
        actionPanel.add(updateButton);
        
        panel.add(actionPanel, BorderLayout.SOUTH);
        
        // 添加事件监听器
        addEventListeners();
        
        return panel;
    }
    
    /**
     * 创建统计信息面板
     */
    private JPanel createStatsPanel() {
        JPanel panel = new JPanel(new GridLayout(4, 1, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        JLabel titleLabel = new JLabel("商品统计信息", JLabel.CENTER);
        titleLabel.setFont(new Font("宋体", Font.BOLD, 18));
        
        JLabel statsLabel = new JLabel(getStatisticsInfo(), JLabel.LEFT);
        statsLabel.setVerticalAlignment(SwingConstants.TOP);
        
        JButton refreshStatsButton = new JButton("刷新统计");
        refreshStatsButton.addActionListener(e -> statsLabel.setText(getStatisticsInfo()));
        
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(refreshStatsButton);
        
        panel.add(titleLabel);
        panel.add(statsLabel);
        panel.add(new JLabel("")); // 空白标签用于布局
        panel.add(buttonPanel);
        
        return panel;
    }
    
    /**
     * 创建关于面板
     */
    private JPanel createAboutPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        
        JTextArea aboutArea = new JTextArea();
        aboutArea.setEditable(false);
        aboutArea.setLineWrap(true);
        aboutArea.setWrapStyleWord(true);
        
        StringBuilder aboutText = new StringBuilder();
        aboutText.append("电商系统商品管理\n\n");
        aboutText.append("版本: 1.0\n\n");
        aboutText.append("功能介绍:\n");
        aboutText.append("1. 支持多种商品类型管理（电子产品、服装、食品、书籍）\n");
        aboutText.append("2. 商品的添加、删除、查询功能\n");
        aboutText.append("3. 商品库存管理\n");
        aboutText.append("4. 商品类型统计\n");
        aboutText.append("5. 文件存储持久化\n\n");
        aboutText.append("系统特性:\n");
        aboutText.append("- 面向对象设计，易于扩展\n");
        aboutText.append("- 图形用户界面，操作便捷\n");
        aboutText.append("- 异常处理机制完善\n");
        aboutText.append("- 支持多种商品类型\n");
        
        aboutArea.setText(aboutText.toString());
        
        panel.add(new JScrollPane(aboutArea), BorderLayout.CENTER);
        
        return panel;
    }
    
    /**
     * 添加事件监听器
     */
    private void addEventListeners() {
        searchButton.addActionListener(e -> searchProducts());
        refreshButton.addActionListener(e -> refreshProductList());
        
        addButton.addActionListener(e -> showAddProductDialog());
        
        deleteButton.addActionListener(e -> deleteSelectedProduct());
        
        updateButton.addActionListener(e -> updateSelectedProduct());
        
        // 按Enter键搜索
        searchField.addActionListener(e -> searchProducts());
    }
    
    /**
     * 刷新商品列表，按类型分类显示，并合并重复商品
     */
    private void refreshProductList() {
        productListModel.clear();
        List<Product> products = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
        
        // 合并重复商品
        List<Product> mergedProducts = mergeDuplicateProducts(products);
        
        // 保存合并后的商品回文件
        ProductStorage.saveProducts(mergedProducts, PRODUCT_FILE_PATH);
        
        // 按类型分组商品
        List<Product> electronics = new ArrayList<>();
        List<Product> clothing = new ArrayList<>();
        List<Product> food = new ArrayList<>();
        List<Product> books = new ArrayList<>();
        
        for (Product product : mergedProducts) {
            if (product instanceof ElectronicProduct) {
                electronics.add(product);
            } else if (product instanceof ClothingProduct) {
                clothing.add(product);
            } else if (product instanceof FoodProduct) {
                food.add(product);
            } else if (product instanceof BookProduct) {
                books.add(product);
            }
        }
        
        // 添加分隔符和类型标题
        addProductsByCategory("===== 电子产品 =====", electronics);
        addProductsByCategory("===== 服装商品 =====", clothing);
        addProductsByCategory("===== 食品商品 =====", food);
        addProductsByCategory("===== 书籍商品 =====", books);
        
        // 清空详情区域
        detailsArea.setText("");
    }
    
    /**
     * 合并重复商品，根据商品名称和类型判断重复
     * @param products 原始商品列表
     * @return 合并后的商品列表
     */
    private List<Product> mergeDuplicateProducts(List<Product> products) {
        // 使用Map来跟踪已经处理过的商品，键为商品名称+类型
        Map<String, Product> uniqueProducts = new HashMap<>();
        int mergeCount = 0; // 记录合并的商品数量
        
        for (Product product : products) {
            // 创建一个唯一键，基于商品名称和类型
            String productType = getProductType(product);
            String key = product.getName() + "_" + productType;
            
            if (uniqueProducts.containsKey(key)) {
                // 找到重复商品，合并库存
                Product existingProduct = uniqueProducts.get(key);
                int originalStock = existingProduct.getStock();
                existingProduct.addStock(product.getStock());
                mergeCount++;
            } else {
                // 新商品，添加到map中
                uniqueProducts.put(key, product);
            }
        }
        
        // 如果有合并操作，显示提示信息
        if (mergeCount > 0) {
            System.out.println("已合并 " + mergeCount + " 个重复商品");
        }
        
        // 返回合并后的商品列表
        return new ArrayList<>(uniqueProducts.values());
    }
    
    /**
     * 按类别添加商品到列表
     */
    private void addProductsByCategory(String categoryTitle, List<Product> products) {
        if (!products.isEmpty()) {
            // 添加类别标题作为不可选择的标记行
            productListModel.addElement("--------------------");
            productListModel.addElement(categoryTitle);
            
            // 添加该类别下的所有商品
            for (Product product : products) {
                String productType = getProductType(product);
                productListModel.addElement("  " + product.getProductId() + ": " + product.getName() + " (" + productType + ")");
            }
        }
    }
    
    /**
     * 显示选中商品的详细信息
     */
    private void showProductDetails() {
        int selectedIndex = productList.getSelectedIndex();
        if (selectedIndex >= 0) {
            // 获取列表中选中的文本
            String selectedText = productList.getSelectedValue().toString();
            
            // 跳过分隔符和类别标题行
            if (selectedText.startsWith("--------------------") || 
                selectedText.startsWith("=====") || 
                selectedText.trim().isEmpty()) {
                detailsArea.setText("");
                return;
            }
            
            // 加载所有商品并找到对应的实际商品
            List<Product> products = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
            
            // 按类型分组商品，与显示顺序一致
            List<Product> sortedProducts = new ArrayList<>();
            List<Product> electronics = new ArrayList<>();
            List<Product> clothing = new ArrayList<>();
            List<Product> food = new ArrayList<>();
            List<Product> books = new ArrayList<>();
            
            for (Product product : products) {
                if (product instanceof ElectronicProduct) {
                    electronics.add(product);
                } else if (product instanceof ClothingProduct) {
                    clothing.add(product);
                } else if (product instanceof FoodProduct) {
                    food.add(product);
                } else if (product instanceof BookProduct) {
                    books.add(product);
                }
            }
            
            // 按显示顺序添加所有商品
            sortedProducts.addAll(electronics);
            sortedProducts.addAll(clothing);
            sortedProducts.addAll(food);
            sortedProducts.addAll(books);
            
            // 计算实际商品索引（跳过标题和分隔符）
            int productCount = 0;
            int realIndex = -1;
            
            for (int i = 0; i < selectedIndex; i++) {
                String itemText = productListModel.getElementAt(i).toString();
                if (!itemText.startsWith("--------------------") && 
                    !itemText.startsWith("=====") && 
                    !itemText.trim().isEmpty()) {
                    productCount++;
                }
            }
            
            // 检查是否是有效商品
            if (productCount < sortedProducts.size()) {
                Product selectedProduct = sortedProducts.get(productCount);
                detailsArea.setText(selectedProduct.getDetails());
            }
        }
    }
    
    /**
     * 搜索商品
     */
    private void searchProducts() {
        String keyword = searchField.getText().trim();
        if (!keyword.isEmpty()) {
            List<Product> searchResults = ProductStorage.findProductsByName(keyword, PRODUCT_FILE_PATH);
            
            if (searchResults.isEmpty()) {
                JOptionPane.showMessageDialog(this, "未找到匹配的商品", 
                        "搜索结果", JOptionPane.INFORMATION_MESSAGE);
            } else {
                productListModel.clear();
                
                // 按类型分组搜索结果
                List<Product> electronics = new ArrayList<>();
                List<Product> clothing = new ArrayList<>();
                List<Product> food = new ArrayList<>();
                List<Product> books = new ArrayList<>();
                
                for (Product product : searchResults) {
                    if (product instanceof ElectronicProduct) {
                        electronics.add(product);
                    } else if (product instanceof ClothingProduct) {
                        clothing.add(product);
                    } else if (product instanceof FoodProduct) {
                        food.add(product);
                    } else if (product instanceof BookProduct) {
                        books.add(product);
                    }
                }
                
                // 添加搜索结果的标题
                productListModel.addElement("===== 搜索结果 =====");
                
                // 按类别添加搜索结果
                // 自定义搜索结果的分类标题添加方式，避免重复的分隔符
                if (!electronics.isEmpty()) {
                    productListModel.addElement("--------------------");
                    productListModel.addElement("电子产品");
                    for (Product product : electronics) {
                        String productType = getProductType(product);
                        productListModel.addElement("  " + product.getProductId() + ": " + product.getName() + " (" + productType + ")");
                    }
                }
                if (!clothing.isEmpty()) {
                    productListModel.addElement("--------------------");
                    productListModel.addElement("服装商品");
                    for (Product product : clothing) {
                        String productType = getProductType(product);
                        productListModel.addElement("  " + product.getProductId() + ": " + product.getName() + " (" + productType + ")");
                    }
                }
                if (!food.isEmpty()) {
                    productListModel.addElement("--------------------");
                    productListModel.addElement("食品商品");
                    for (Product product : food) {
                        String productType = getProductType(product);
                        productListModel.addElement("  " + product.getProductId() + ": " + product.getName() + " (" + productType + ")");
                    }
                }
                if (!books.isEmpty()) {
                    productListModel.addElement("--------------------");
                    productListModel.addElement("书籍商品");
                    for (Product product : books) {
                        String productType = getProductType(product);
                        productListModel.addElement("  " + product.getProductId() + ": " + product.getName() + " (" + productType + ")");
                    }
                }
                
                JOptionPane.showMessageDialog(this, "找到 " + searchResults.size() + " 个匹配的商品", 
                        "搜索结果", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
    
    /**
     * 更新选中的商品
     */
    private void updateSelectedProduct() {
        int selectedIndex = productList.getSelectedIndex();
        if (selectedIndex == -1) {
            JOptionPane.showMessageDialog(this, "请先选择要更新的商品", 
                    "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 获取选中的文本，检查是否是有效商品
        String selectedText = productList.getSelectedValue().toString();
        if (selectedText.startsWith("--------------------") || 
            selectedText.startsWith("=====") || 
            selectedText.trim().isEmpty()) {
            JOptionPane.showMessageDialog(this, "请选择有效的商品，不要选择分类标题", 
                    "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        // 加载所有商品并按类别排序
        List<Product> allProducts = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
        
        // 按类型分组商品，与显示顺序一致
        List<Product> sortedProducts = new ArrayList<>();
        List<Product> electronics = new ArrayList<>();
        List<Product> clothing = new ArrayList<>();
        List<Product> food = new ArrayList<>();
        List<Product> books = new ArrayList<>();
        
        for (Product product : allProducts) {
            if (product instanceof ElectronicProduct) {
                electronics.add(product);
            } else if (product instanceof ClothingProduct) {
                clothing.add(product);
            } else if (product instanceof FoodProduct) {
                food.add(product);
            } else if (product instanceof BookProduct) {
                books.add(product);
            }
        }
        
        // 按显示顺序添加所有商品
        sortedProducts.addAll(electronics);
        sortedProducts.addAll(clothing);
        sortedProducts.addAll(food);
        sortedProducts.addAll(books);
        
        // 计算实际商品索引（跳过标题和分隔符）
        int productCount = 0;
        
        for (int i = 0; i < selectedIndex; i++) {
            String itemText = productListModel.getElementAt(i).toString();
            if (!itemText.startsWith("--------------------") && 
                !itemText.startsWith("=====") && 
                !itemText.trim().isEmpty()) {
                productCount++;
            }
        }
        
        // 检查索引是否有效
        if (productCount < sortedProducts.size()) {
            Product selectedProduct = sortedProducts.get(productCount);
            showUpdateProductDialog(selectedProduct);
        } else {
            JOptionPane.showMessageDialog(this, "无法找到选中的商品", 
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 显示更新商品对话框
     */
    private void showUpdateProductDialog(Product product) {
        JDialog updateDialog = new JDialog(this, "更新商品", true);
        updateDialog.setSize(600, 400);
        updateDialog.setLocationRelativeTo(this);
        
        JPanel productPanel = null;
        
        // 根据商品类型创建对应的表单面板
        if (product instanceof ElectronicProduct) {
            productPanel = createElectronicProductUpdateForm(updateDialog, (ElectronicProduct) product);
        } else if (product instanceof ClothingProduct) {
            productPanel = createClothingProductUpdateForm(updateDialog, (ClothingProduct) product);
        } else if (product instanceof FoodProduct) {
            productPanel = createFoodProductUpdateForm(updateDialog, (FoodProduct) product);
        } else if (product instanceof BookProduct) {
            productPanel = createBookProductUpdateForm(updateDialog, (BookProduct) product);
        }
        
        if (productPanel != null) {
            updateDialog.add(productPanel);
            updateDialog.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this, "未知的商品类型", 
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    /**
     * 创建电子产品更新表单
     */
    private JPanel createElectronicProductUpdateForm(JDialog dialog, ElectronicProduct product) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField(product.getProductId());
        idField.setEditable(false); // 商品ID不可编辑
        JTextField nameField = new JTextField(product.getName());
        JTextField priceField = new JTextField(String.valueOf(product.getPrice()));
        JTextField descriptionField = new JTextField(product.getDescription());
        JTextField stockField = new JTextField(String.valueOf(product.getStock()));
        
        // 特有字段
        JTextField brandField = new JTextField(product.getBrand());
        JTextField modelField = new JTextField(product.getModel());
        JTextField warrantyField = new JTextField(String.valueOf(product.getWarrantyPeriod()));
        JTextField specsField = new JTextField(product.getSpecs());
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("品牌 *:"));
        specificPanel.add(brandField);
        
        specificPanel.add(new JLabel("型号 *:"));
        specificPanel.add(modelField);
        
        specificPanel.add(new JLabel("保修期(月) *:"));
        specificPanel.add(warrantyField);
        
        specificPanel.add(new JLabel("技术规格:"));
        specificPanel.add(specsField);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    brandField.getText().trim().isEmpty() || modelField.getText().trim().isEmpty() ||
                    warrantyField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建更新后的电子产品
                ElectronicProduct updatedProduct = new ElectronicProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    brandField.getText().trim(),
                    modelField.getText().trim(),
                    Integer.parseInt(warrantyField.getText().trim()),
                    specsField.getText().trim()
                );
                
                // 保存更新后的商品
                boolean updated = updateProductInStorage(updatedProduct);
                if (updated) {
                    JOptionPane.showMessageDialog(dialog, "商品更新成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品更新失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "更新商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建服装商品更新表单
     */
    private JPanel createClothingProductUpdateForm(JDialog dialog, ClothingProduct product) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField(product.getProductId());
        idField.setEditable(false); // 商品ID不可编辑
        JTextField nameField = new JTextField(product.getName());
        JTextField priceField = new JTextField(String.valueOf(product.getPrice()));
        JTextField descriptionField = new JTextField(product.getDescription());
        JTextField stockField = new JTextField(String.valueOf(product.getStock()));
        
        // 特有字段
        ClothingProduct cp = (ClothingProduct) product;
        JTextField sizeField = new JTextField(cp.getSize());
        JTextField colorField = new JTextField(cp.getColor());
        JTextField materialField = new JTextField(cp.getMaterial());
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女", "中性"});
        genderComboBox.setSelectedItem(cp.getGender());
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("尺码 *:"));
        specificPanel.add(sizeField);
        
        specificPanel.add(new JLabel("颜色 *:"));
        specificPanel.add(colorField);
        
        specificPanel.add(new JLabel("材质 *:"));
        specificPanel.add(materialField);
        
        specificPanel.add(new JLabel("适用性别 *:"));
        specificPanel.add(genderComboBox);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    sizeField.getText().trim().isEmpty() || colorField.getText().trim().isEmpty() ||
                    materialField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建更新后的服装商品
                ClothingProduct updatedProduct = new ClothingProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    sizeField.getText().trim(),
                    colorField.getText().trim(),
                    materialField.getText().trim(),
                    (String) genderComboBox.getSelectedItem()
                );
                
                // 保存更新后的商品
                boolean updated = updateProductInStorage(updatedProduct);
                if (updated) {
                    JOptionPane.showMessageDialog(dialog, "商品更新成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品更新失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "更新商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建食品商品更新表单
     */
    private JPanel createFoodProductUpdateForm(JDialog dialog, FoodProduct product) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField(product.getProductId());
        idField.setEditable(false); // 商品ID不可编辑
        JTextField nameField = new JTextField(product.getName());
        JTextField priceField = new JTextField(String.valueOf(product.getPrice()));
        JTextField descriptionField = new JTextField(product.getDescription());
        JTextField stockField = new JTextField(String.valueOf(product.getStock()));
        
        // 特有字段
        JTextField expiryDateField = new JTextField(product.getExpiryDate());
        JTextField ingredientsField = new JTextField(product.getIngredients());
        JTextField nutritionalField = new JTextField(product.getNutritionalInfo());
        JCheckBox organicCheckBox = new JCheckBox("有机食品");
        organicCheckBox.setSelected(product.isOrganic());
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("保质期(YYYY-MM-DD) *:"));
        specificPanel.add(expiryDateField);
        
        specificPanel.add(new JLabel("成分 *:"));
        specificPanel.add(ingredientsField);
        
        specificPanel.add(new JLabel("营养信息:"));
        specificPanel.add(nutritionalField);
        
        specificPanel.add(new JLabel("有机食品:"));
        specificPanel.add(organicCheckBox);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    expiryDateField.getText().trim().isEmpty() || ingredientsField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建更新后的食品商品
                FoodProduct updatedProduct = new FoodProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    expiryDateField.getText().trim(),
                    ingredientsField.getText().trim(),
                    nutritionalField.getText().trim(),
                    organicCheckBox.isSelected()
                );
                
                // 保存更新后的商品
                boolean updated = updateProductInStorage(updatedProduct);
                if (updated) {
                    JOptionPane.showMessageDialog(dialog, "商品更新成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品更新失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "更新商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建书籍商品更新表单
     */
    private JPanel createBookProductUpdateForm(JDialog dialog, BookProduct product) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField(product.getProductId());
        idField.setEditable(false); // 商品ID不可编辑
        JTextField nameField = new JTextField(product.getName());
        JTextField priceField = new JTextField(String.valueOf(product.getPrice()));
        JTextField descriptionField = new JTextField(product.getDescription());
        JTextField stockField = new JTextField(String.valueOf(product.getStock()));
        
        // 特有字段
        JTextField authorField = new JTextField(product.getAuthor());
        JTextField publisherField = new JTextField(product.getPublisher());
        JTextField publishYearField = new JTextField(String.valueOf(product.getPublishYear()));
        JTextField isbnField = new JTextField(product.getIsbn());
        JTextField genreField = new JTextField(product.getGenre());
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(5, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("作者 *:"));
        specificPanel.add(authorField);
        
        specificPanel.add(new JLabel("出版社 *:"));
        specificPanel.add(publisherField);
        
        specificPanel.add(new JLabel("出版年份 *:"));
        specificPanel.add(publishYearField);
        
        specificPanel.add(new JLabel("ISBN *:"));
        specificPanel.add(isbnField);
        
        specificPanel.add(new JLabel("书籍类型:"));
        specificPanel.add(genreField);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    authorField.getText().trim().isEmpty() || publisherField.getText().trim().isEmpty() ||
                    publishYearField.getText().trim().isEmpty() || isbnField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建更新后的书籍商品
                BookProduct updatedProduct = new BookProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    authorField.getText().trim(),
                    publisherField.getText().trim(),
                    Integer.parseInt(publishYearField.getText().trim()),
                    isbnField.getText().trim(),
                    genreField.getText().trim()
                );
                
                // 保存更新后的商品
                boolean updated = updateProductInStorage(updatedProduct);
                if (updated) {
                    JOptionPane.showMessageDialog(dialog, "商品更新成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品更新失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "更新商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 在存储中更新商品
     * @param updatedProduct 更新后的商品
     * @return 更新成功返回true，否则返回false
     */
    private boolean updateProductInStorage(Product updatedProduct) {
        List<Product> products = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
        boolean found = false;
        
        // 查找并替换商品
        for (int i = 0; i < products.size(); i++) {
            if (products.get(i).getProductId().equals(updatedProduct.getProductId())) {
                products.set(i, updatedProduct);
                found = true;
                break;
            }
        }
        
        // 如果找到并替换了商品，则保存到文件
        if (found) {
            return ProductStorage.saveProducts(products, PRODUCT_FILE_PATH);
        }
        return false;
    }
    
    /**
     * 删除选中的商品
     */
    private void deleteSelectedProduct() {
        int selectedIndex = productList.getSelectedIndex();
        if (selectedIndex >= 0) {
            List<Product> products = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
            if (selectedIndex < products.size()) {
                Product productToDelete = products.get(selectedIndex);
                int confirm = JOptionPane.showConfirmDialog(this, 
                        "确定要删除商品: " + productToDelete.getName() + "?", 
                        "确认删除", JOptionPane.YES_NO_OPTION);
                
                if (confirm == JOptionPane.YES_OPTION) {
                    boolean deleted = ProductStorage.deleteProduct(productToDelete.getProductId(), PRODUCT_FILE_PATH);
                    if (deleted) {
                        JOptionPane.showMessageDialog(this, "商品删除成功", 
                                "成功", JOptionPane.INFORMATION_MESSAGE);
                        refreshProductList();
                    } else {
                        JOptionPane.showMessageDialog(this, "商品删除失败", 
                                "错误", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        } else {
            JOptionPane.showMessageDialog(this, "请先选择要删除的商品", 
                    "提示", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
    /**
     * 获取商品类型名称
     */
    private String getProductType(Product product) {
        if (product instanceof ElectronicProduct) return "电子产品";
        else if (product instanceof ClothingProduct) return "服装";
        else if (product instanceof FoodProduct) return "食品";
        else if (product instanceof BookProduct) return "书籍";
        else return "未知类型";
    }
    
    /**
     * 获取统计信息
     */
    private String getStatisticsInfo() {
        List<Product> products = ProductStorage.loadProducts(PRODUCT_FILE_PATH);
        int total = products.size();
        int electronicCount = 0, clothingCount = 0, foodCount = 0, bookCount = 0;
        
        for (Product product : products) {
            if (product instanceof ElectronicProduct) electronicCount++;
            else if (product instanceof ClothingProduct) clothingCount++;
            else if (product instanceof FoodProduct) foodCount++;
            else if (product instanceof BookProduct) bookCount++;
        }
        
        StringBuilder stats = new StringBuilder();
        stats.append("总商品数: " + total + "\n\n");
        stats.append("商品类型统计:\n");
        stats.append("- 电子产品: " + electronicCount + " (" + getPercentage(electronicCount, total) + "%)\n");
        stats.append("- 服装: " + clothingCount + " (" + getPercentage(clothingCount, total) + "%)\n");
        stats.append("- 食品: " + foodCount + " (" + getPercentage(foodCount, total) + "%)\n");
        stats.append("- 书籍: " + bookCount + " (" + getPercentage(bookCount, total) + "%)\n");
        
        // 计算总库存
        int totalStock = 0;
        for (Product product : products) {
            totalStock += product.getStock();
        }
        stats.append("\n总库存量: " + totalStock);
        
        return stats.toString();
    }
    
    /**
     * 计算百分比
     */
    private double getPercentage(int count, int total) {
        if (total == 0) return 0;
        return Math.round((count * 100.0 / total) * 10) / 10.0;
    }
    
    /**
     * 显示添加商品对话框
     */
    private void showAddProductDialog() {
        JDialog addDialog = new JDialog(this, "添加商品", true);
        addDialog.setSize(600, 400);
        addDialog.setLocationRelativeTo(this);
        
        // 创建选项卡面板，根据商品类型显示不同的表单
        JTabbedPane productTypeTabs = new JTabbedPane();
        
        // 添加不同类型商品的表单面板
        productTypeTabs.addTab("电子产品", createElectronicProductForm(addDialog));
        productTypeTabs.addTab("服装", createClothingProductForm(addDialog));
        productTypeTabs.addTab("食品", createFoodProductForm(addDialog));
        productTypeTabs.addTab("书籍", createBookProductForm(addDialog));
        
        addDialog.add(productTypeTabs);
        addDialog.setVisible(true);
    }
    
    /**
     * 创建通用的商品属性面板
     */
    private JPanel createCommonProductPanel(JTextField idField, JTextField nameField, 
                                          JTextField priceField, JTextField descriptionField, 
                                          JTextField stockField) {
        JPanel panel = new JPanel(new GridLayout(5, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        panel.add(new JLabel("商品编号 *:"));
        panel.add(idField);
        
        panel.add(new JLabel("商品名称 *:"));
        panel.add(nameField);
        
        panel.add(new JLabel("商品价格 *:"));
        panel.add(priceField);
        
        panel.add(new JLabel("商品描述:"));
        panel.add(descriptionField);
        
        panel.add(new JLabel("库存数量 *:"));
        panel.add(stockField);
        
        return panel;
    }
    
    /**
     * 创建提交按钮面板
     */
    private JPanel createSubmitButtonPanel(JDialog dialog, Runnable submitAction) {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());
        
        JButton submitButton = new JButton("添加");
        submitButton.addActionListener(e -> {
            submitAction.run();
        });
        
        panel.add(cancelButton);
        panel.add(submitButton);
        
        return panel;
    }
    
    /**
     * 创建电子产品表单
     */
    private JPanel createElectronicProductForm(JDialog dialog) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField descriptionField = new JTextField();
        JTextField stockField = new JTextField();
        
        // 特有字段
        JTextField brandField = new JTextField();
        JTextField modelField = new JTextField();
        JTextField warrantyField = new JTextField();
        JTextField specsField = new JTextField();
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("品牌 *:"));
        specificPanel.add(brandField);
        
        specificPanel.add(new JLabel("型号 *:"));
        specificPanel.add(modelField);
        
        specificPanel.add(new JLabel("保修期(月) *:"));
        specificPanel.add(warrantyField);
        
        specificPanel.add(new JLabel("技术规格:"));
        specificPanel.add(specsField);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (idField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    brandField.getText().trim().isEmpty() || modelField.getText().trim().isEmpty() ||
                    warrantyField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建电子产品
                ElectronicProduct product = new ElectronicProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    brandField.getText().trim(),
                    modelField.getText().trim(),
                    Integer.parseInt(warrantyField.getText().trim()),
                    specsField.getText().trim()
                );
                
                // 保存商品
                boolean saved = ProductStorage.saveSingleProduct(product, PRODUCT_FILE_PATH);
                if (saved) {
                    JOptionPane.showMessageDialog(dialog, "商品添加成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品添加失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "添加商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建服装商品表单
     */
    private JPanel createClothingProductForm(JDialog dialog) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField descriptionField = new JTextField();
        JTextField stockField = new JTextField();
        
        // 特有字段
        JTextField sizeField = new JTextField();
        JTextField colorField = new JTextField();
        JTextField materialField = new JTextField();
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女", "中性"});
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("尺码 *:"));
        specificPanel.add(sizeField);
        
        specificPanel.add(new JLabel("颜色 *:"));
        specificPanel.add(colorField);
        
        specificPanel.add(new JLabel("材质 *:"));
        specificPanel.add(materialField);
        
        specificPanel.add(new JLabel("适用性别 *:"));
        specificPanel.add(genderComboBox);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (idField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    sizeField.getText().trim().isEmpty() || colorField.getText().trim().isEmpty() ||
                    materialField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建服装商品
                ClothingProduct product = new ClothingProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    sizeField.getText().trim(),
                    colorField.getText().trim(),
                    materialField.getText().trim(),
                    (String) genderComboBox.getSelectedItem()
                );
                
                // 保存商品
                boolean saved = ProductStorage.saveSingleProduct(product, PRODUCT_FILE_PATH);
                if (saved) {
                    JOptionPane.showMessageDialog(dialog, "商品添加成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品添加失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "添加商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建食品商品表单
     */
    private JPanel createFoodProductForm(JDialog dialog) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField descriptionField = new JTextField();
        JTextField stockField = new JTextField();
        
        // 特有字段
        JTextField expiryDateField = new JTextField();
        JTextField ingredientsField = new JTextField();
        JTextField nutritionalField = new JTextField();
        JCheckBox organicCheckBox = new JCheckBox("有机食品");
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("保质期(YYYY-MM-DD) *:"));
        specificPanel.add(expiryDateField);
        
        specificPanel.add(new JLabel("成分 *:"));
        specificPanel.add(ingredientsField);
        
        specificPanel.add(new JLabel("营养信息:"));
        specificPanel.add(nutritionalField);
        
        specificPanel.add(new JLabel("有机食品:"));
        specificPanel.add(organicCheckBox);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (idField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    expiryDateField.getText().trim().isEmpty() || ingredientsField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建食品商品
                FoodProduct product = new FoodProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    expiryDateField.getText().trim(),
                    ingredientsField.getText().trim(),
                    nutritionalField.getText().trim(),
                    organicCheckBox.isSelected()
                );
                
                // 保存商品
                boolean saved = ProductStorage.saveSingleProduct(product, PRODUCT_FILE_PATH);
                if (saved) {
                    JOptionPane.showMessageDialog(dialog, "商品添加成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品添加失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "添加商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 创建书籍商品表单
     */
    private JPanel createBookProductForm(JDialog dialog) {
        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        
        // 通用字段
        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JTextField priceField = new JTextField();
        JTextField descriptionField = new JTextField();
        JTextField stockField = new JTextField();
        
        // 特有字段
        JTextField authorField = new JTextField();
        JTextField publisherField = new JTextField();
        JTextField publishYearField = new JTextField();
        JTextField isbnField = new JTextField();
        JTextField genreField = new JTextField();
        
        // 通用属性面板
        JPanel commonPanel = createCommonProductPanel(idField, nameField, priceField, descriptionField, stockField);
        
        // 特有属性面板
        JPanel specificPanel = new JPanel(new GridLayout(5, 2, 10, 10));
        specificPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
        
        specificPanel.add(new JLabel("作者 *:"));
        specificPanel.add(authorField);
        
        specificPanel.add(new JLabel("出版社 *:"));
        specificPanel.add(publisherField);
        
        specificPanel.add(new JLabel("出版年份 *:"));
        specificPanel.add(publishYearField);
        
        specificPanel.add(new JLabel("ISBN *:"));
        specificPanel.add(isbnField);
        
        specificPanel.add(new JLabel("书籍类型:"));
        specificPanel.add(genreField);
        
        // 创建提交动作
        Runnable submitAction = () -> {
            try {
                // 验证必填字段
                if (idField.getText().trim().isEmpty() || nameField.getText().trim().isEmpty() ||
                    priceField.getText().trim().isEmpty() || stockField.getText().trim().isEmpty() ||
                    authorField.getText().trim().isEmpty() || publisherField.getText().trim().isEmpty() ||
                    publishYearField.getText().trim().isEmpty() || isbnField.getText().trim().isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写所有必填字段（标*的字段）", 
                            "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                
                // 创建书籍商品
                BookProduct product = new BookProduct(
                    idField.getText().trim(),
                    nameField.getText().trim(),
                    Double.parseDouble(priceField.getText().trim()),
                    descriptionField.getText().trim(),
                    Integer.parseInt(stockField.getText().trim()),
                    authorField.getText().trim(),
                    publisherField.getText().trim(),
                    Integer.parseInt(publishYearField.getText().trim()),
                    isbnField.getText().trim(),
                    genreField.getText().trim()
                );
                
                // 保存商品
                boolean saved = ProductStorage.saveSingleProduct(product, PRODUCT_FILE_PATH);
                if (saved) {
                    JOptionPane.showMessageDialog(dialog, "商品添加成功！", 
                            "成功", JOptionPane.INFORMATION_MESSAGE);
                    dialog.dispose();
                    refreshProductList();
                } else {
                    JOptionPane.showMessageDialog(dialog, "商品添加失败！", 
                            "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException e) {
                JOptionPane.showMessageDialog(dialog, "请输入有效的数字！", 
                        "错误", JOptionPane.ERROR_MESSAGE);
            } catch (InvalidPriceException e) {
                JOptionPane.showMessageDialog(dialog, e.getMessage(), 
                        "价格错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception e) {
                JOptionPane.showMessageDialog(dialog, "添加商品时出错: " + e.getMessage(), 
                        "错误", JOptionPane.ERROR_MESSAGE);
            }
        };
        
        // 添加所有面板
        JPanel fieldsPanel = new JPanel(new BorderLayout());
        fieldsPanel.add(commonPanel, BorderLayout.NORTH);
        fieldsPanel.add(specificPanel, BorderLayout.CENTER);
        
        mainPanel.add(fieldsPanel, BorderLayout.CENTER);
        mainPanel.add(createSubmitButtonPanel(dialog, submitAction), BorderLayout.SOUTH);
        
        return mainPanel;
    }
    
    /**
     * 主方法，启动GUI应用
     */
    public static void main(String[] args) {
        // 在事件调度线程中运行GUI
        SwingUtilities.invokeLater(() -> {
            ProductGUI gui = new ProductGUI();
            gui.setVisible(true);
        });
    }
}